package com.eclink.asset.asset.service;

import com.alibaba.fastjson.JSON;
import com.eclink.asset.asset.domain.dao.AssetApplyRelItem;
import com.eclink.asset.asset.domain.dao.AssetItem;
import com.eclink.asset.asset.domain.dao.AssetRepair;
import com.eclink.asset.asset.domain.dao.FlowApply;
import com.eclink.asset.asset.domain.form.ApplyFormDataZCWX;
import com.eclink.asset.asset.mapper.AssetRepairMapper;
import com.eclink.asset.domain.dto.FlowApplyDetailDTO;
import com.eclink.asset.enums.AssetItemStateEnum;
import com.eclink.asset.workflow.service.ApplyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AssetRepairService {

    @Resource
    private ApplyService service;

    @Resource
    private AssetRepairMapper assetRepairMapper;

    @Resource
    private AssetItemService assetItemService;

    public void add(AssetRepair entity) {
        assetRepairMapper.insert(entity);
    }

    @Transactional
    public void finish(String applyId, AssetRepair repair) {
        service.finish(applyId);
        FlowApply apply = service.getById(applyId);
        ApplyFormDataZCWX formData = JSON.parseObject(apply.getFormData(), ApplyFormDataZCWX.class);
        List<AssetApplyRelItem> items = formData.getItems();
        for (AssetApplyRelItem item : items) {
            AssetItem assetItem = assetItemService.selectById(item.getSourceId());
            assetItem.setState(AssetItemStateEnum.DRAFT.getValue());
            assetItemService.update(assetItem);
        }
        repair.setApplyId(applyId);
        this.add(repair);
    }


}
